Page({
  data: {
    goodsList: [],
    isLoggedIn: false,
    showLoginModal: false
  },
  onLoad() {
    this.checkLoginStatus();
    this.getGoodsList();
  },
  onShow() {
    this.checkLoginStatus();
  },
  checkLoginStatus() {
    // 检查本地存储的登录状态
    const userInfo = wx.getStorageSync('userInfo');
    this.setData({
      isLoggedIn: !!userInfo
    });
  },
  getGoodsList() {
    // 请求后端商品列表
    wx.request({
      url: 'http://localhost:3000/api/goods',
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.code === 0) {
          this.setData({
            goodsList: res.data.data
          });
        }
      },
      fail() {
        wx.showToast({ title: '获取商品失败', icon: 'none' });
      }
    });
  },
  addToCart(e) {
    const goodsId = e.currentTarget.dataset.id;
    
    // 检查是否已登录
    if (!this.data.isLoggedIn) {
      this.setData({ showLoginModal: true });
      return;
    }
    
    // 已登录，直接添加到购物车
    const userInfo = wx.getStorageSync('userInfo');
    wx.request({
      url: 'http://localhost:3000/api/cart',
      method: 'POST',
      data: {
        user_id: userInfo.id,
        goods_id: goodsId,
        quantity: 1
      },
      success(res) {
        if (res.data && res.data.code === 0) {
          wx.showToast({ title: '已加入购物车', icon: 'success' });
        } else {
          wx.showToast({ title: res.data.message || '加入失败', icon: 'none' });
        }
      },
      fail() {
        wx.showToast({ title: '加入失败', icon: 'none' });
      }
    });
  },
  goToLogin() {
    this.setData({ showLoginModal: false });
    wx.navigateTo({
      url: '/pages/user/login/index'
    });
  },
  closeLoginModal() {
    this.setData({ showLoginModal: false });
  }
}); 